<script setup lang="ts">
  import { ref } from 'vue'
  import { useCustomerServiceOptions, useCustomerServiceForm } from './services'
  import { FormInstance } from 'element-plus'
  import { UpdateCustomerServiceFormReturn } from './updateCustomerServiceFormTypes'

  const { form, submitLoading, submit } = useCustomerServiceForm()
  const { customerServiceOptions, getCustomerServiceOptionsLoading, getCustomerServiceOptions } =
    useCustomerServiceOptions()

  const props = defineProps<{
    currentEmp?: string
  }>()

  const formRef = ref<FormInstance | null>(null)
  const rules = ref({
    empId: [{ required: true, message: '请选择客服人员！', trigger: ['blur', 'change'] }],
  })
  const getCustomerServiceOptionsKeyword = ref('')
  const getCustomerServiceOptionsFn = () => {
    getCustomerServiceOptions(getCustomerServiceOptionsKeyword.value)
  }

  defineExpose({
    submitLoading,
    getCustomerServiceOptionsFn,
    submit: async (orderId: string) => {
      let result: null | UpdateCustomerServiceFormReturn = null
      if (!formRef.value) {
        return result
      }
      try {
        await formRef.value.validate()
        result = await submit(orderId)
      } catch (error) {
        // 不可以删除改注释，否则会引起eslint的报错
        // 也不可以删除catch块，否则会引起控制台的报错
        return result
      }
      return result
    },
  })
</script>

<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    class="modal_form_content"
    label-position="top"
    inline-message
  >
    <el-form-item label="分配客服" required prop="empId">
      <el-select
        v-model="form.empId"
        placeholder="分配客服"
        :loading="getCustomerServiceOptionsLoading"
      >
        <template #header>
          <div class="select_header">
            <el-input
              v-model.trim="getCustomerServiceOptionsKeyword"
              placeholder="请输入关键字"
              @keyup.enter="getCustomerServiceOptionsFn"
            />
            <HPlainButton @click="getCustomerServiceOptionsFn">搜索</HPlainButton>
          </div>
        </template>
        <el-option
          v-for="item in customerServiceOptions"
          :key="item.name"
          :disabled="props.currentEmp === item.name"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="处理备注" prop="remark">
      <el-input
        v-model.trim="form.remark"
        type="textarea"
        maxlength="200"
        show-word-limit
        resize="both"
        placeholder="请输入处理备注"
      />
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
  .select_header {
    display: flex;
    gap: 5px;
  }

  :deep(.el-textarea) {
    .el-textarea__inner {
      min-height: 75px !important;
      width: 100% !important;
      max-height: 140px !important;
      overflow: hidden;
    }
  }
</style>
